package red.internal.client.net;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import red.client.config.RedConfig;
import red.internal.core.message.Code;
import red.internal.core.message.HandshakeMessage;

/**
 * @author Jin Zheng
 * @since 2019-05-03
 */
public class HandshakeHandler extends SimpleChannelInboundHandler<HandshakeMessage>
{
	private static Logger logger = LoggerFactory.getLogger(HandshakeHandler.class);

	private final DefaultRedClient client;
	private final RedConfig redConfig;
	private Channel channel;

	public HandshakeHandler(DefaultRedClient client)
	{
		this.client = client;
		this.redConfig = client.getRedConfig();
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, HandshakeMessage response) throws Exception
	{
		if (response.getCode() == Code.SUCCESS)
		{
			logger.info("Handshake successful");
			client.getChannelClient().addChannel(channel);
		}
		else
		{
			logger.warn("0x{}: {}", Integer.toHexString(response.getCode().value()), response.getMessage());
			client.stop();
		}
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception
	{
		channel = ctx.channel();
		HandshakeMessage request = HandshakeMessage.create(redConfig.getToken());
		ctx.writeAndFlush(request);
		logger.info("Handshake to {}: {}", client.getRemoteAddress(), redConfig.getToken());

		super.channelActive(ctx);
	}

}
